<?php
namespace Home\Controller;
use Think\Controller;

class AccountController extends CommonController {
    public function index(){
        $this->display();
    }
    public function test(){
        $res=$this->cl_sms('13587989359','测试','0100010020');
        var_dump($res);
    }
    public function get_oss(){
        header("Access-Control-Allow-Origin: *");
        $res['oss_appid'] = 'LTAI6sZcsEa0SGHc'; //OSS的APPID
        $res['oss_secret'] = '053o9lXKyeLh1J1nmlykMg0z8N0Q5E'; //OSS的APP_SECRET
        $res['oss_url'] = 'xycha.oss-cn-hangzhou.aliyuncs.com';  //OSS的服务器地址
        $res['oss_bucket'] = 'xycha';  //OSS的bucket
        $res['oss_file'] = 'xyc';  //OSS的文件夹路径
        $data['ret']='1001';
        $data['code']='success';
        $data['dara']=$res;
        echo json_encode($data);
        exit;
    }
    public function Charging($shop_identifier,$mobile,$detail){
        $merchant = M('merchant','',C('DB2'))->field("consume_type,consume_value")->where(array('shop_identifier'=>$shop_identifier))->find();
        $consume_type = $merchant['consume_type'];
        $consume_value = $merchant['consume_value']*0.01;
        $price = M('price','',C('DB2'))->where(array('id'=>1))->getField("money");
        if($consume_type==2){
            if($merchant['consume_value']<100){
                $money = $price;
            }else{
                $money = $price*$merchant['consume_value'];
            }
        }elseif($consume_type==3){
            $money =M('price','',C('DB2'))->where(array('id'=>6))->getField("money");
        }else{
            $money = $price;
        }
        $url = "http://dnqxfv2.hzdouniu.cn/haoxin/deducted";
        $add= array(
            'shopIdentifier'=>$shop_identifier,
            'mobile'=>$mobile,
            'money'=>$money,
            'detail'=>$detail,
            'type'=>'1',
            'costType'=>'1',
        );

        $result = $this->curl_post_https($url,$add);
        $result = json_decode($result,true);
        return $result;
    }

    function curl_post_https($url,$data){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容    
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式

    }


    public function channel_status(){
        header("Access-Control-Allow-Origin: *");
        $channel = I('channel');

        if(empty($channel)){
            $this->return = ['ret' => '1002','code'=>'系统错误，请联系客服'];
            return false;
        }
        $status = M('channel','',C('DB2'))->where(Array('chan_id'=>$channel))->getField("state");
        if($status==2){
            $data['ret']='1001';
            $data['code']='该渠道号正常';
            echo json_encode($data);
            exit;
        }elseif($status==1){
            $data['ret']='1002';
            $data['code']='该渠道号已下架';
            echo json_encode($data);
            exit;
        }elseif($status==-1){
            $data['ret']='1002';
            $data['code']='该渠道号已删除';
            echo json_encode($data);
            exit;
        }else{
            $data['ret']='1002';
            $data['code']='系统错误，请联系客服';
            echo json_encode($data);
            exit;
        }

    }

    public function delete_ceshi(){
        $mobile =I('mobile');
        if(empty($mobile)){
            echo json_encode(['ret'=>'1002','code'=>'mobile error']);
            exit();
        }
        if($mobile!='13282380039'&&$mobile!='15394272274'){
            echo json_encode(['ret'=>'1002','code'=>'mobile error']);
            exit();
        }
        $has = M('user','',C('DB2'))->where(['mobile'=>$mobile,'is_delete'=>'1'])->getField('id');
        if($has){
            M('user','',C('DB2'))->where(['mobile'=>$mobile])->delete();
            echo json_encode(['ret'=>'1001','code'=>'success']);
            exit();
        }
        echo json_encode(['ret'=>'1001','code'=>'success']);
        exit();
    }
    public function web_page(){
        header("Access-Control-Allow-Origin: *");
        $channel = I('channel');
        $shop_identifier = M('channel','',C('DB2'))->where(Array('chan_id'=>$channel))->field('shop_identifier,style_id')->find();
        $data = M('shop_style','',C('DB2'))->where(array('shop_identifier'=>$shop_identifier['shop_identifier'],'id'=>$shop_identifier['style_id'],'status'=>'2'))->find();
        $this->return = ['ret' => '1001','code'=>'success','data'=>$data];
        return false;
    }
    public function verify(){
        header("Access-Control-Allow-Origin: *");
        ob_clean();
        $ss=I('ss');
        $config =    array(    'fontSize'    =>    50,    // 验证码字体大小
            'length'      =>    3,     // 验证码位数
            'useNoise'    =>    false, // 关闭验证码杂点
            'model'=>1,
            'useCurve'=>false,
            'useImgBg'=>false,
        );
        $Verify =     new \Think\Verify($config);
        $Verify->codeSet = '0123456789';
        $ip=get_client_ip();
        $Verify->entry($ip);
    }
    public function web_code_img(){
        header("Access-Control-Allow-Origin: *");
        ob_clean();
        session_start();
        $ss = I('ss');
        $config =    array(    'fontSize'    =>    50,    // 验证码字体大小
            'length'      =>    3,     // 验证码位数
            'useNoise'    =>    false, // 关闭验证码杂点
            'model'=>1,
            'useCurve'=>false,
            'useImgBg'=>false,
        );
        $Verify =     new \Think\Verify($config);
        $Verify->codeSet = '0123456789';
        $ip=get_client_ip();
        $Verify->entry($ip);
    }
    public function isMobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备
        if (isset ($_SERVER['HTTP_VIA']))
        {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT']))
        {
            $clientkeywords = array ('nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT']))
        {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
            {
                return true;
            }
        }
        return false;
    }
    public function login_attestation(){

        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        //if ($this->isMobile)//是否是手机用户
        //{
            $ip=$_SERVER["REMOTE_ADDR"];//用户ip
            $redis= new \Redis();
            $redis->connect('xycshop0577.redis.rds.aliyuncs.com');  //地址与端口
            $redis->auth('Dstl0577');  ///密码
            $channel_num=I('channelNum');
        $cx_date=date('Y-m-d');//查询时间
            if($redis ->get( "login_attestation".$ip.$channel_num.$cx_date)){
                $browse = M('browse','',C('DB2'))->where(["channel_num"=>$channel_num,'dtime'=>$cx_date])->field('id,server_id')->find();
                if(empty($browse)){
                    $data['dtime']=date('Y-m-d');//时间
                    $data['channel_num']=$channel_num;//渠道号
                    $channel = M('channel','',C('DB2'))->where(['chan_id'=>$channel_num])->field('server_id')->find();
                    $data['server_id']=$channel['server_id'];
                    $data['num']=0;
                    M('browse','',C('DB2'))->add($data);
                }
                //M('browse','',C('DB2'))->where(['channel_num'=>$channel_num])->setInc('num');
            }else{

                $redis ->set("login_attestation".$ip.$channel_num.$cx_date, $ip,86400);
//                $browse = M('browse','',C('DB2'))->where(["channel_num"=>$channel_num])->field('id,server_id')->find();
//                if($browse){
//                    M('browse','',C('DB2'))->where(['channel_num'=>$channel_num])->setInc('num');
//                    if($browse['server_id']==0){
//                        $channel = M('channel','',C('DB2'))->where(['chan_id'=>$channel_num])->getField('server_id');
//                        if($channel){
//                            M('browse','',C('DB2'))->where(['channel_num'=>$channel_num])->save(['server_id'=>$channel]);
//                        }
//                    }
//                }else{
//                    if(!empty($channel_num)){
//                        $data['dtime']=date('Y-m-d H:i:s');//时间
//                        $data['channel_num']=$channel_num;//渠道号
//                        $channel = M('channel','',C('DB2'))->where(['chan_id'=>$channel_num])->field('server_id')->find();
//                        $data['server_id']=$channel['server_id'];
//                        $data['num']=1;
//                        M('browse','',C('DB2'))->add($data);
//                    }
//                }                        $channel = M('channel', '', C('DB2'))->where(['chan_id' => $channel_num])->getField('server_id');
                $server_id = M('channel', '', C('DB2'))->where(['chan_id' => $channel_num])->getField('server_id');

                $browse = M('browse','',C('DB2'))->where(["channel_num"=>$channel_num,'dtime'=>$cx_date,'server_id'=>$server_id])->field('id,server_id')->find();
                if($browse){
                    M('browse','',C('DB2'))->where(['channel_num'=>$channel_num,'dtime'=>$cx_date,'server_id'=>$server_id])->setInc('num');
//                    if($browse['server_id']==0) {
//                        $channel = M('channel', '', C('DB2'))->where(['chan_id' => $channel_num])->getField('server_id');
//                        if($channel){
//                            M('browse','',C('DB2'))->where(['channel_num'=>$channel_num,'dtime'=>$cx_date])->save(['server_id'=>$channel]);
//                        }
//                    }
                }else{
                        $data['dtime']=date('Y-m-d');//时间
                        $data['channel_num']=$channel_num;//渠道号
                        $channel = M('channel','',C('DB2'))->where(['chan_id'=>$channel_num])->field('server_id,shop_identifier')->find();
                        $data['server_id']=$channel['server_id'];
                    $data['shop_identifier']=$channel['shop_identifier'];
                        $data['num']=1;
                        M('browse','',C('DB2'))->add($data);
                }
            }
       // }
        $this->display();
    }
    public function login_attestation1(){
        $this->display();
    }
    public function web_login_msg(){
        header("Access-Control-Allow-Origin: *");
        $mobile = I('mobile');
        $verify =     new \Think\Verify();
        $verify->useImgBg = true;
        $verify_code=I('verify');
        $identity_num  = I('identity_num');
        $ss=I('ss');
        $channel = I('channel');
        $ip=get_client_ip();

//        if($channel=='123456'){
//            $yzm= new YzmController();
//            $check=$yzm->verify($verify_code,$ip);//二次验证
//        }else{
//            $check=$verify->check($verify_code,$ip);
//        }
        //$yzm= new YzmController();
        $check=$this->verifyy($verify_code,$ip);//二次验证
        //$check=true;
        $shop_identifier = M('channel','',C('DB2'))->where(['chan_id'=>$channel,'state'=>'2'])->field('shop_identifier,channel_name')->find();
        if(empty($shop_identifier)){
            if(empty($mobile)){
                $this->return = ['ret' => '1002','code'=>'该注册页面已失效'];
                return false;
            }
        }
        $user_login_data = M('user_login','',C('DB2'))->where(array('mobile'=>$mobile,'shop_identifier'=>$shop_identifier['shop_identifier'],'status'=>['not in','4']))->getField('id');
        if(empty($mobile)){
            $this->return = ['ret' => '1002','code'=>'请先输入手机号码'];
            return false;
        }
//        if(empty($identity_num)){
//            $this->return = ['ret' => '1002','code'=>'请先填写身份证号'];
//            return false;
//        }
        if($user_login_data){
            $this->return = ['ret' => '1003','code'=>'该手机号码已被注册'];
            return false;
        }
//        $has_idcard = M('user','',C('DB2'))->where(array('identity_num'=>$identity_num,'shop_identifier'=>$shop_identifier['shop_identifier']))->getField('id');
//        if($has_idcard){
//            $this->return = ['ret' => '1003','code'=>'该身份证已被注册'];
//            return false;
//        }
        if(empty($channel)||empty($shop_identifier)){
            $this->return = ['ret' => '1002','code'=>'请获取正确的渠道链接'];
            return false;
        }
        if(!$check){
            $this->return = ['ret' => '1002','code'=>'请检查滑块验证码是否正确'];
            return false;
        }
        if(!preg_match("/1[3456789]{1}\d{9}$/",$mobile)||empty($mobile)){
            $data['ret']='1002';
            $data['code']='手机号码格式有误';
            echo json_encode($data);
            exit;
        }
        $phonecode=rand(100000,999999);
        //$code=(string)rand(1000,9999);//语音验证码
        //$mobilecode="     $code[0]     $code[1]     $code[2]     $code[3]";//语音验证码/带空格
        $time=S($mobile,'phonechang_time');
        $count=S($mobile.'count');
        if(time()-$time>120&&$count<8)
        //if(time()-$time>120||$mobile=='15858787556'||$mobile=='15225170185'||$mobile=='18658805071')
        {
            S($mobile.'phonechang_verify',$phonecode);
            S($mobile.'phonechang_time',time());
           $content = '验证码为'.$phonecode.',您正在登陆，请勿将验证码透露给他人。';
            $shop_identifier = M('channel','',C('DB2'))->where(array('chan_id'=>$channel))->getField('shop_identifier');
            /************************注册短信扣费************************/
            $detail = "注册短信获取费用";
            $result = $this->Charging($shop_identifier,$mobile,$detail);
            if($result['isSuccess']!=0){
                $status=$this->cl_sms($mobile,$content,$shop_identifier);
                //$status=$this->voice_code($mobile,$mobilecode);
                //            if($status)
//                if($status['code']=='1001')
                if($status)
                {
                    $data['ret']='1001';
                    $data['code']='短信验证码已成功发送,请注意接收';
                    echo json_encode($data);
                    exit;
                }
                else
                {
                    $data['ret']='1002';
                    $data['code']='短信验证码发送失败,请联系管理员';
                    echo json_encode($data);
                    exit;
                }
            }else{
                $data['ret']='1002';
                $data['code']='发送失败,请联系管理员!';
                echo json_encode($data);
                exit;
            }


        } else
        {
            $data['ret']='1002';
            $data['code']='短信验证码之间发送间隔为3分钟，且每日只能发送8条';
            echo json_encode($data);
            exit;
        }
    }
    public function get_app(){//获取渠道下载地址以及客服信息
        $channel 		=  I('channel');
//        $channel 		= '049eb8181b8d42b0ac6476cfadd21f05';
        $mobile         = I('mobile');
        if(empty($channel)){
            $data['ret']='1002';
            $data['code']='失败，未获取到渠道号';
            echo json_encode($data);
            exit();
        }
        $shop_identifier = M('channel','',C('DB2'))->where(['chan_id'=>$channel])->field('shop_identifier,shop_id')->find();
        $appurl = M('merchant','',C('DB2'))->where(['shop_identifier'=>$shop_identifier['shop_identifier']])->field('app_url,ios_url')->find();
        $chat_data = M('communication','',C('DB2'))->where(['shop_id'=>$shop_identifier['shop_id']])->field('qq,wx')->find();
        $data['ret']='1001';
        $data['code']='成功';
        $data['url']=$appurl;
        $data['chat_data']=$chat_data;
        echo json_encode($data);
        exit();
    }
    public function web_acc(){
        header("Access-Control-Allow-Origin: *");
        // session_start();
        if(!IS_POST){
            $data['ret']='1002';
            $data['code']='NOT POST';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        $mobile = I('mobile'); // 手机号码
        $code 		=  I('code'); // 验证码
        $name     = I('name');
        $id_card  = I('id_card');
        $channel 		=  I('channel');
         $browser=I('browser');
        $operation=I('operation');
        $shop_identifier = M('channel','',C('DB2'))->where(['chan_id'=>$channel])->field('shop_identifier,channel_name,shop_id,server_id')->find();
        if(empty($shop_identifier['shop_identifier'])){
            $data['ret']='1002';
            $data['code']='请输入正确的渠道号';
            echo json_encode($data);
            exit;
        }
        $user_login_data = M('user_login','',C('DB2'))->where(array('mobile'=>$mobile,'shop_identifier'=>$shop_identifier['shop_identifier'],'status'=>['not in','4']))->getField('id');
//        $user_data = M('user','',C('DB2'))->where(['mobile'=>$mobile,'shop_identifier'=>$shop_identifier])->getField('identity_num');
//        if($user_data==$id_card){
//            $data['ret']='1002';
//            $data['code']='该身份证已被注册';
//            echo json_encode($data);
//            exit;
//        }
        if(!preg_match("/1[3456789]{1}\d{9}$/",$mobile)||empty($mobile)){
            $data['ret']='1002';
            $data['code']='手机号码格式有误';
            echo json_encode($data);
            exit;
        }
        if($user_login_data){
            $data['ret']='1002';
            $data['code']='手机号已存在!';
            echo json_encode($data);
            exit();
        }

        if(empty($code)){
            $data['ret']='1002';
            $data['code']='验证码不能为空';
            echo json_encode($data);
            exit();
        }
        $time = S($mobile.'phonechang_time');
        $redcode = S($mobile.'phonechang_verify');
        if($mobile!='17742050062'&&$mobile!='15225170185'&&$mobile!='13003940779'){
            if(time()-$time>120||$redcode!=$code){
                $data['ret']='1002';
                $data['code']='验证码错误或过期';
                echo json_encode($data);
                exit();
            }
        }

        S($mobile.'phonechang_time',null);
        S($mobile.'phonechang_verify',null);
        M('user','',C('DB2'))->startTrans();
        $data['mobile']			= $mobile;
        $data['ctime']			= time();
        $data['username']			= $name;
        $data['identity_num']			= $id_card;
        $data['server_id']			= $shop_identifier['server_id'];
        $kf_id = explode(',',$shop_identifier['shop_id']);
        $data['chat_id']			= $kf_id[array_rand($kf_id)];
        $data['channel']			= empty($channel)?'':$channel;
        $data['shop_identifier']			= empty($shop_identifier['shop_identifier'])?'':$shop_identifier['shop_identifier'];
        $register = M('user','',C('DB2'))->lock(true)->add($data); // 用户基本信息
        $userlogin['mobile']=$mobile;
        $ip = $this->get_ip2();  // IP 省 市
        $userlogin['register_ip']  	= $ip['ip']; // 注册IP
        $userlogin['city']			= empty($ip['city'])?'未知':$ip['city'];
        $userlogin['province']   	= empty($ip['shenfen'])?'未知':$ip['shenfen'];
        $userlogin['shop_identifier'] = $shop_identifier['shop_identifier'];
        $userlogin['channel'] = $channel;
        $userlogin['user_id'] = $register;
        $userlogin['ctime'] = time();
        $userlogin['browser'] = $browser;
        $userlogin['acc_operation'] = $operation;
        $res_login=M('user_login','',C('DB2'))->add($userlogin);
        $apply_order_data['shop_identifier']=$shop_identifier['shop_identifier'];
        $apply_order_data['channel_num']=$channel;
        $apply_order_data['order_num']=date('YmdHis').rand(100000,999999);
        $apply_order_data['channel_name']=$shop_identifier['channel_name'];
        $apply_order_data['apply_user']=$name;
        $apply_order_data['user_mobile']=$mobile;
        $apply_order_data['apply_time']=time();
        $apply_order_data['user_id']=$register;
        M('apply_order','',C('DB2'))->add($apply_order_data);
        $userData['user_id'] = $register;
        $userData['ctime'] = time();
        $userData['mobile'] = $mobile;
        M('user_authentication','',C('DB2'))->add(array('user_id'=>$register,'ctime'=>time()));

        if ($res_login) {
            M('user','',C('DB2'))->commit();
            $has_marketing =M('marketing','',C('DB2'))->where(['mobile'=>$mobile])->getField('id');
            if($has_marketing){
                M('marketing','',C('DB2'))->where(['mobile'=>$mobile])->setField('id_delete','2');
            }
            $label = M('label','',C('DB2'))->where(['shop_identifier'=>$shop_identifier['shop_identifier'],'name'=>'无标签'])->getField('id');
            M('label_id','',C('DB2'))->add(['user_id'=>$register,'label_id'=>$label,'ctime'=>time()]);

            $data['ret']='1001';
            $data['code']='成功';
            echo json_encode($data);

            $gateway = new \Home\Service\Gateway();
            $label = M('user', Null, 'DB2')
                ->join("u left join label_id l_id on u.id=l_id.user_id")
                ->join("left join label l on l.id=l_id.label_id")
                ->join("left join user_identity uid on uid.user_id=u.id")
                ->where(["u.id" =>$register, 'u.is_delete' => 1])
                ->order("l.name desc")
                ->field("l.id,l_id.user_id,l.name,u.username,uid.hold")
                ->group("u.id")
                //->fetchSql(true)
                ->select();
            //$updata_user_list = json_encode($label);
            $data7['type'] = 'update_user_list';
            $data7['data'] = $label;
            $user_chat_id=M('user','','DB2')->where(['id'=>$register])->getField('chat_id');
            $chat_account=M('shopkeeper','','DB2')->where(['id'=>$user_chat_id,'state'=>1])->field('account')->find();
            //if($gateway->isUidOnline($chat_account['account'])==1){
                $gateway->sendToUid($chat_account['account'], json_encode($data7));//像对方发送消息
//            }else{
//            M('','','DB2')
//            }
            exit();
        }else {
            M('user','',C('DB2'))->rollback();
            $data['ret']='1002';
            $data['code']='注册失败';
            echo json_encode($data);
            exit();
        }
    }
    public function web_acc1(){
        header("Access-Control-Allow-Origin: *");
        // session_start();
        if(!IS_POST){
            $data['ret']='1002';
            $data['code']='NOT POST';
//            $data = $this->jiami($data);
            echo json_encode($data);
//            $this->return = ['data'=>$data];
            exit();
        }
        $mobile = I('mobile'); // 手机号码
        $code 		=  I('code'); // 验证码
        $name     = I('name');
//        $id_card  = I('id_card');
        $operation = I('operation');
        $browser = I('browser');
        $channel 		=  I('channel');
        $shop_identifier = M('channel','',C('DB2'))->where(['chan_id'=>$channel])->field('shop_identifier,channel_name,shop_id')->find();
        if(empty($shop_identifier['shop_identifier'])){
            $data['ret']='1002';
            $data['code']='请输入正确的渠道号';
            echo json_encode($data);
            exit;
        }
        $user_login_data = M('user_login','',C('DB2'))->where(array('mobile'=>$mobile,'shop_identifier'=>$shop_identifier['shop_identifier'],'status'=>['not in','4']))->getField('id');
        if(!preg_match("/1[3456789]{1}\d{9}$/",$mobile)||empty($mobile)){
            $data['ret']='1002';
            $data['code']='手机号码格式有误';
            echo json_encode($data);
            exit;
        }
        if($user_login_data){
            $data['ret']='1002';
            $data['code']='手机号已存在!';
            echo json_encode($data);
            exit();
        }

        if(empty($code)){
            $data['ret']='1002';
            $data['code']='验证码不能为空';
            echo json_encode($data);
            exit();
        }
        $time = S($mobile.'phonechang_time');
        $redcode = S($mobile.'phonechang_verify');
        //if($mobile!='17742050062'&&$mobile!='13003940779'&&$mobile!='18658805071'){
            if(time()-$time>120||$redcode!=$code){
                $data['ret']='1002';
                $data['code']='验证码错误';
                echo json_encode($data);
                exit();
            }
        //}

        S($mobile.'phonechang_time',null);
        S($mobile.'phonechang_verify',null);
        M('user','',C('DB2'))->startTrans();
        $data['mobile']			= $mobile;
        $data['ctime']			= time();
        $data['username']			= $name;
        $kf_id = explode(',',$shop_identifier['shop_id']);
        $data['chat_id']			= $kf_id[array_rand($kf_id)];
        $data['channel']			= empty($channel)?'':$channel;
        $data['shop_identifier']			= empty($shop_identifier['shop_identifier'])?'':$shop_identifier['shop_identifier'];
        $register = M('user','',C('DB2'))->add($data); // 用户基本信息
        $userlogin['mobile']=$mobile;
        $ip = $this->get_ip2();  // IP 省 市
        $userlogin['register_ip']  	= $ip['ip']; // 注册IP
        $userlogin['city']			= empty($ip['city'])?'未知':$ip['city'];
        $userlogin['province']   	= empty($ip['shenfen'])?'未知':$ip['shenfen'];
        $userlogin['shop_identifier'] = $shop_identifier['shop_identifier'];
        $userlogin['channel'] = $channel;
        $userlogin['user_id'] = $register;
        $userlogin['ctime'] = time();
        $userlogin['acc_operation'] = $operation;
        $userlogin['browser'] = $browser;
        $res_login=M('user_login','',C('DB2'))->add($userlogin);
        $apply_order_data['shop_identifier']=$shop_identifier['shop_identifier'];
        $apply_order_data['channel_num']=$channel;
        $apply_order_data['order_num']=date('YmdHis').rand(100000,999999);
        $apply_order_data['channel_name']=$shop_identifier['channel_name'];
        $apply_order_data['apply_user']=$name;
        $apply_order_data['user_mobile']=$mobile;
        $apply_order_data['apply_time']=time();
        $apply_order_data['user_id']=$register;
        M('apply_order','',C('DB2'))->add($apply_order_data);
        $userData['user_id'] = $register;
        $userData['ctime'] = time();
        $userData['mobile'] = $mobile;
        M('user_authentication','',C('DB2'))->add(array('user_id'=>$register,'ctime'=>time()));

        if ($res_login) {
            M('user','',C('DB2'))->commit();
            $has_marketing =M('marketing','',C('DB2'))->where(['mobile'=>$mobile])->getField('id');
            if($has_marketing){
                M('marketing','',C('DB2'))->where(['mobile'=>$mobile])->setField('id_delete','2');
            }
            //$label = M('label','',C('DB2'))->where(['shop_identifier'=>$shop_identifier['shop_identifier'],'name'=>'无标签'])->getField('id');
            //M('label_id','',C('DB2'))->add(['user_id'=>$register,'label_id'=>$label,'ctime'=>time()]);
            $data['ret']='1001';
            $data['code']='成功';
            echo json_encode($data);
            exit();
        }else {
            M('user','',C('DB2'))->rollback();
            $data['ret']='1002';
            $data['code']='注册失败';
            echo json_encode($data);
            exit();
        }
    }
    public function sessintest(){
        $res = $_SESSION;
        var_dump($res);
    }
    public function login_code(){
        header("Content-Type: text/html; charset=UTF-8");
        $data1=I('data');
        $get=$this->jiemi($data1);
        $mobile = $get['mobile'];
        $verify =     new \Think\Verify();
        $verify_code=$get['verify'];
        $ss=$get['ss'];
        $device=$get['device'];
        $shop_identifier = $get['shop_identifier'];
        $ip=get_client_ip();
//        if($shop_identifier=='0100010020'||$shop_identifier=='0100030016'||$shop_identifier=='0100030015'||$shop_identifier=='0100030018'||$shop_identifier=='0100010003'){
////            //$yzm= new YzmController();
////            $check=$this->verifyy($verify_code,$ip);//二次验证
////            if(!$check){
//////                $data['ret']='1002';
//////                $data['code']='滑块验证码错误';
//////                $data1 = $this->jiami($data);
//////                $this->return = ['data'=>$data1];
//////                exit;
//////            }
////        }else{
////            $check=$verify->check($verify_code,$ip);
////            if(!$check&&$device!='android'){
////                $data['ret']='1002';
////                $data['code']='图片验证码错误';
////                $data1 = $this->jiami($data);
////                $this->return = ['data'=>$data1];
////                exit;
////            }
////        }
        if($shop_identifier!='0100020003') {
            $check = $this->verifyy($verify_code, $ip);//二次验证
            if (!$check) {
                $data['ret'] = '1002';
                $data['code'] = '滑块验证码错误';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                exit;
            }
        }

        if(!preg_match("/1[3456789]{1}\d{9}$/",$mobile)||empty($mobile)){
            $data['ret']='1002';
            $data['code']='手机号码格式有误';
            $data1 = $this->jiami($data);
            $this->return = ['data'=>$data1];
            exit;
        }
        $phonecode=rand(100000,999999);
        //$code=(string)rand(1000,9999);//语音验证码
        //$mobilecode="     $code[0]     $code[1]     $code[2]     $code[3]";//语音验证码/带空格
        $time=S($mobile,'phonechang_time');
        $count=S($mobile.'count');
        if(time()-$time>120&&$count<8)
        //if(time()-$time>59||$mobile=='15858787556'||$mobile=='15225170185'||$mobile=='18658805071')
        {
            S($mobile.'phonechang_verify',$phonecode);
            S($mobile.'phonechang_time',time());
            $content = '验证码为'.$phonecode.',您正在登陆，请勿将验证码透露给他人。';
            /************************注册短信扣费************************/
            $detail = "注册短信扣费";
            $result = $this->Charging($shop_identifier,$mobile,$detail);
            if($result['isSuccess']!=0||$mobile=='15225170185'){
                $status=$this->cl_sms($mobile,$content,$shop_identifier);
                //$status=$this->voice_code($mobile,$mobilecode);//语音验证码
                if($status)
                {
                    $data['ret']='1001';
                    $data['code']='短信验证码已成功发送,请注意接收';
                    $data1 = $this->jiami($data);
                    $this->return = ['data'=>$data1];
                    exit;
                }
                else
                {
                    $data['ret']='1002';
                    $data['code']='短信验证码发送失败,请联系管理员';
                    $data1 = $this->jiami($data);
                    $this->return = ['data'=>$data1];
                    exit;
                }
            }else{
                $data['ret']='1002';
                $data['code']='发送失败,请联系管理员';
                $data1 = $this->jiami($data);
                $this->return = ['data'=>$data1];
                exit;
            }

        }
        else
        {
            $data['ret']='1002';
            $data['code']='短信验证码之间发送间隔为3分钟，且每日只能发送8条';
            $data1 = $this->jiami($data);
            $this->return = ['data'=>$data1];
            exit;
        }
    }

    public function login_verify(){
        header("Content-Type: text/html; charset=UTF-8");
        $data1=I('data');
        $get=$this->jiemi($data1);
        $mobile = $get['mobile'];
        $verify =     new \Think\Verify();
        $verify_code=$get['verify'];
        $ss=$get['ss'];
        $device=$get['device'];
        $shop_identifier = $get['shop_identifier'];
        $ip=get_client_ip();
//        if($shop_identifier=='0100010020'||$shop_identifier=='0100030016'||$shop_identifier=='0100030015'||$shop_identifier=='0100030018'||$shop_identifier=='0100010003'){
//            //$yzm= new YzmController();
//            $check=$this->verifyy($verify_code,$ip);//二次验证
//            if(!$check){
//                $data['ret']='1002';
//                $data['code']='滑块验证码错误';
//                $data1 = $this->jiami($data);
//                $this->return = ['data'=>$data1];
//                exit;
//            }
//        }else{
//            $check=$verify->check($verify_code,$ip);
//            if(!$check&&$device!='android'){
//                $data['ret']='1002';
//                $data['code']='图片验证码错误';
//                $data1 = $this->jiami($data);
//                $this->return = ['data'=>$data1];
//                exit;
//            }
//        }
        $check=$this->verifyy($verify_code,$ip);//二次验证
        if(!$check){
            $data['ret']='1002';
            $data['code']='滑块验证码错误';
            $data1 = $this->jiami($data);
            $this->return = ['data'=>$data1];
            exit;
        }
        if(!preg_match("/1[3456789]{1}\d{9}$/",$mobile)||empty($mobile)){
            $data['ret']='1002';
            $data['code']='手机号码格式有误';
            $data1 = $this->jiami($data);
            $this->return = ['data'=>$data1];
            exit;
        }
        $phonecode=rand(100000,999999);
        //$code=(string)rand(1000,9999);//语音验证码
        //$mobilecode="     $code[0]     $code[1]     $code[2]     $code[3]";//语音验证码/带空格
        $time=S($mobile,'phone_time');
        if(time()-$time>120||$mobile=='17742050062'||$mobile=='15858787556'||$mobile=='15225170185'||$mobile=='18658805071')
        {
            S($mobile.'phone_verify',$phonecode);
            S($mobile.'phone_time',time());
            $content = '验证码为'.$phonecode.',您正在登陆，请勿将验证码透露给他人。';
            /************************登陆短信扣费************************/
            $detail = "登陆短信扣费";
            $result = $this->Charging($shop_identifier,$mobile,$detail);
            if($result['isSuccess']!=0||$mobile='15225170185'){
                $status=$this->cl_sms($mobile,$content,$shop_identifier);
                //$status=$this->voice_code($mobile,$mobilecode);
                //if($status['code']='1001')
                if($status)
                {
                    // $add= array(
                    //     'shop_identifier'=>$shop_identifier,
                    //     'mobile'=>$mobile,
                    //     'money'=>'0.05',
                    //     'detail'=>'登陆短信扣费',
                    //     'type'=>'1',
                    //     'ctime'=>time(),
                    // );
                    // M('balance_record','',C('DB2'))->add($add);//短信扣费
                    // M('merchant','',C('DB2'))->where(array('shop_identifier'=>$shop_identifier))->setDec('msg_balance',0.05);
                    $data['ret']='1001';
                    $data['code']='短信验证码已成功发送,请注意接收';
                    $data1 = $this->jiami($data);
                    $this->return = ['data'=>$data1];
                    exit;
                }
                else
                {
                    $data['ret']='1002';
                    $data['code']='短信验证码发送失败,请联系管理员';
                    $data1 = $this->jiami($data);
                    $this->return = ['data'=>$data1];
                    exit;
                }
            }else{
                $data['ret']='1002';
                $data['code']='发送失败,请联系管理员';
                $data1 = $this->jiami($data);
                $this->return = ['data'=>$data1];
                exit;
            }

        }
        else
        {
            $data['ret']='1002';
            $data['code']='短信验证码之间发送间隔为3分钟，且每日只能发送8条';
            $data1 = $this->jiami($data);
            $this->return = ['data'=>$data1];
            exit;
        }
    }
    /// 找回密码
    public function backpwd_code(){
        header("Content-Type: text/html; charset=UTF-8");
        $data1=I('data');
        $get=$this->jiemi($data1);
        $mobile = $get['mobile'];
        $shop_identifier=$get['shop_identifier'];
        $verify_code=$get['verify'];///验证码
        $ip=get_client_ip();
        $res = M('user','',C('DB2'))->where(array('mobile'=>$mobile,'shop_identifier'=>$shop_identifier,'is_delete'=>'1'))->field('id')->find();
        if(!preg_match("/1[345789]{1}\d{9}$/",$mobile)){
            $data['ret']='1002';
            $data['code']='手机号码格式不正确';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        if(empty($res)){
            $data['ret']='1002';
            $data['code']='手机号不存在';
            $data['zhuagntai']=$res;
            $data['zhuangtai1']=$mobile;
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
//        if($shop_identifier=='0100010020'||$shop_identifier=='0100030016'||$shop_identifier=='0100030015'||$shop_identifier=='0100030018'||$shop_identifier=='0100010003') {
//            //$yzm = new YzmController();
//            $check=$this->verifyy($verify_code,$ip);//二次验证
//            if (!$check) {
//                $data['ret'] = '1002';
//                $data['code'] = '滑块验证码错误';
//                $data1 = $this->jiami($data);
//                $this->return = ['data' => $data1];
//                exit;
//            }
//        }
//        }else{
//            $check=$verify->check($verify_code,$ip);
//            if(!$check&&$device!='android'){
//                $data['ret']='1002';
//                $data['code']='图片验证码错误';
//                $data1 = $this->jiami($data);
//                $this->return = ['data'=>$data1];
//                exit;
//            }
//        }
        if($shop_identifier!='0100020003') {
            $check = $this->verifyy($verify_code, $ip);//二次验证
            if (!$check) {
                $data['ret'] = '1002';
                $data['code'] = '滑块验证码错误';
                $data1 = $this->jiami($data);
                $this->return = ['data' => $data1];
                exit;
            }
        }
        $phonecode=rand(100000,999999);//老验证码
        //$code=(string)rand(1000,9999);//语音验证码
        //$mobilecode="     $code[0]     $code[1]     $code[2]     $code[3]";//语音验证码/带空格
        $time=S($mobile,'backpwd_time');
        if(time()-$time>59)
        {
            S($mobile.'backpwd_verify',$phonecode);
            S($mobile.'backpwd_time',time());
            $content = '验证码为'.$phonecode.',您正在找回密码，请勿将验证码透露给他人。';
            /************************修改密码获取短信************************/
            $detail = "修改密码获取短信";
            $result = $this->Charging($shop_identifier,$mobile,$detail);
            if($result['isSuccess']!=0){
                $status=$this->cl_sms($mobile,$content,$shop_identifier);
                //$status=$this->voice_code($mobile,$mobilecode);///语音验证码
                if($status)
                {
                    // $add= array(
                    //     'shop_identifier'=>$shop_identifier,
                    //     'mobile'=>$mobile,
                    //     'money'=>'0.05',
                    //     'detail'=>'修改密码获取短信',
                    //     'type'=>'1',
                    //     'ctime'=>time(),
                    // );
                    // M('balance_record','',C('DB2'))->add($add);//短信扣费
                    // M('merchant','',C('DB2'))->where(array('shop_identifier'=>$shop_identifier))->setDec('msg_balance',0.05);
                    $data['ret']='1001';
                    $data['code']='短信验证码已成功发送,请注意接收';
                    $data1 = $this->jiami($data);
                    $this->return = ['data'=>$data1];
                    exit;
                }
                else
                {
                    $data['ret']='1002';
                    $data['code']='短信验证码发送失败,请联系管理员';
                    $data1 = $this->jiami($data);
                    $this->return = ['data'=>$data1];
                    exit;
                }
            }else{
                $data['ret']='1002';
                $data['code']='发送失败,请联系管理员';
                $data1 = $this->jiami($data);
                $this->return = ['data'=>$data1];
                exit;
            }
        }
        else
        {
            $data['ret']='1002';
            $data['code']='短信验证码之间发送间隔为3分钟，且每日只能发送5条';
            $data1 = $this->jiami($data);
            $this->return = ['data'=>$data1];
            exit;
        }
    }
    /*
    手机号码是否存在
     */
    public static function getAddressComponent($longitude, $latitude, $pois='0'){

        $param = array(
            'ak' => '9VwAKWE6C6sbpoG96rUw0eUmIxu0KoRQ',
            'location' => implode(',', array($latitude, $longitude)),
            'pois' => $pois,
            'output' => 'json'
        );

        // 请求百度api
        $response = self::toCurl('http://api.map.baidu.com/geocoder/v2/', $param);

        $result = array();

        if($response){
            $result = json_decode($response, true);
        }

        return $result;

    }
    private static function toCurl($url, $param=array()){

        $ch = curl_init();

        if(substr($url,0,5)=='https'){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));

        $response = curl_exec($ch);

        if($error=curl_error($ch)){
            return false;
        }

        curl_close($ch);

        return $response;

    }
    public function addresss(){
//        $res1 = $this->getAddressComponent(30.324799,120.159415);
        $res1 = $this->getAddressComponent(120.159415,30.324799);
        var_dump($res1);
    }
    public function model_new(){
        $get = I('data');
        $get = $this->jiemi($get);
        $mobile= $get['mobile'];
        $shop_identifier = $get['shop_identifier'];
//        $mobile= '13180744765';
        $location = $get['location'];
        if(!preg_match("/1[345789]{1}\d{9}$/",$mobile)){
            $data['ret']='1002';
            $data['code']='手机号码格式不正确';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }

        $id = M('user','',C('DB2'))->where(array('mobile'=>$mobile,'shop_identifier'=>$shop_identifier,'is_delete'=>'1'))->field('id')->find();
        $pwd = M('user_login','',C('DB2'))->where(array('mobile'=>$mobile,'shop_identifier'=>$shop_identifier,'status'=>['not in','4']))->field('pwd,shop_identifier,channel,lng_lat')->find();
        if(empty($pwd['pwd'])){
            $data['ret']='1003';
            $data['code']='手机号码不存在';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        if($shop_identifier!=$pwd['shop_identifier']){
            $data['ret']='1003';
            $data['code']='手机号码不存在';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        if(strpos($location,'lat')!==false){
            $coordinate = explode(',', $location);
            $lat = explode(':', $coordinate[0])[1];
            $lon = explode(':', $coordinate[1])[1];
        }else{
            $lat = explode(',', $location)[0];
            $lon = explode(',', $location)[1];
        }
        if($lat>$lon){
            $res = $this->getAddressComponent($lat,$lon);//经度纬度
        }else{
            $res = $this->getAddressComponent($lon,$lat);//经度纬度
        }
        $log = M('user_login_log','',C('DB2'))->where(['user_id'=>$id['id']])->field('address,city')->order('change_time desc')->find();
        if($log['city']!=$res['result']['addressComponent']['city']){

            $data['ret']='1004';
            $data['code']='success';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        if ($id['id']) {
            $data['ret']='1001';
            $data['code']='success';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        } else {
            $data['ret']='1003';
            $data['code']='手机号码不存在';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
    }
    ///加密
    ///
    /*
    注册
    */
    public function register(){
        header("Access-Control-Allow-Origin: *");
        // session_start();
        $get = I('data');
        $get = $this->jiemi($get);

        if(!IS_POST){
            $data['ret']='1002';
            $data['code']='NOT POST';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        $mobile = $get['mobile']; // 手机号码
        $code 		= $get['code']; // 验证码
        $pwd 		= $get['pwd']; // 密码
        $udid = $get['udid'];
        $mobilefirm=$get['mobilefirm'];
        $location  = $get['location'];
        $shop_identifier=$get['shop_identifier'];
        if(empty($shop_identifier)){
            $data['ret']='1002';
            $data['code']='系统错误，请联系客服';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit;
        }
        if(!preg_match("/1[3456789]{1}\d{9}$/",$mobile)||empty($mobile)){
            $data['ret']='1002';
            $data['code']='手机号码格式有误';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit;
        }
        if(!preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/",$pwd)){
            $data['ret']='1002';
            $data['code']='密码必须由字母和数字组成(6-16位)';
            $data['pwd']=$get['pwd'];
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }

        if($shop_identifier!='0100020003') {
            if (empty($code)) {
                $data['ret'] = '1002';
                $data['code'] = '验证码不能为空';
                $data = $this->jiami($data);
                $this->return = ['data' => $data];
                exit();
            }
        }
        $time = S($mobile.'phonechang_time');
        $redcode =S($mobile.'phonechang_verify');
        if($mobile!='15990042951') {//15225170185//$shop_identifier!='0100020003'
            if (time() - $time > 120 || $redcode != $code) {
                $data['ret'] = '1002';
                $data['code'] = '验证码错误';
                $data = $this->jiami($data);
                $this->return = ['data' => $data];
                exit;
            }
        }
        S($mobile.'phonechang_time',null);
        S($mobile.'phonechang_verify',null);
        $data['mobile']			= $mobile;
        $data['pwd']			= md5('hxgj'.$pwd);
        $data['ctime']			= time();
        $data['channel']			= empty($channel_id)?'':$channel_id;
        $data['location']			= $location;
        $data['lon_lat']			= $location;
        $data['shop_identifier']			= $shop_identifier;
        $channel_data = M('channel','',C('DB2'))->where(['shop_identifier'=>$shop_identifier])->getField('shop_id');
        $kefu = $channel_data[array_rand($channel_data)];
        $kefu_id = explode(',',$kefu);
        $kefu_id = $kefu_id[array_rand($kefu_id)];
        $data['chat_id'] = $kefu_id;
        M('user','',C('DB2'))->startTrans();
        $has = M('user','',C('DB2'))->where(['mobile'=>$mobile,'shop_identifier'=>$shop_identifier,'is_delete'=>'1'])->getField('id');
        if(empty($has)){
            $register = M('user','',C('DB2'))->lock(true)->add($data); // 用户基本信息
            $userlogin['mobile']=$mobile;
            $userlogin['pwd']=md5('hxgj'.$pwd);
            $userlogin['udid']=$udid;
            $userlogin['mobilefirm']=$mobilefirm;
            $userlogin['lng_lat']=$location;
            $ip = $this->get_ip2();  // IP 省 市
            $userlogin['register_ip']  	= $ip['ip']; // 注册IP
            $userlogin['city']			= empty($ip['city'])?'未知':$ip['city'];
            $userlogin['province']   	= empty($ip['shenfen'])?'未知':$ip['shenfen'];
            $userlogin['shop_identifier'] = $shop_identifier;
            $userlogin['user_id']=$register;
            $userlogin['ctime']=time();
            $res_login=M('user_login','',C('DB2'))->add($userlogin);
            $apply_order_data['shop_identifier']=$shop_identifier;
            $apply_order_data['channel_num']='';
            $apply_order_data['order_num']=date('YmdHis').rand(100000,999999);
            $apply_order_data['channel_name']='';
            $apply_order_data['user_mobile']=$mobile;
            $apply_order_data['apply_user']='';
            $apply_order_data['apply_time']=time();
            $apply_order_data['user_id']=$register;
            M('apply_order','',C('DB2'))->add($apply_order_data);
            M('user_authentication','',C('DB2'))->add(array('user_id'=>$register,'ctime'=>time()));
        }else{
            $udid = $get['udid'];
            $mobilefirm=$get['mobilefirm'];
            $location  = $get['location'];
            $userlogin['udid']=$udid;
            $userlogin['mobilefirm']=$mobilefirm;
            $userlogin['location']=$location;
            $userlogin['pwd']=md5('hxgj'.$pwd);
            $res_login = M('user_login','',C('DB2'))->where(['mobile'=>$mobile,'shop_identifier'=>$shop_identifier,'status'=>['not in','4']])->save($userlogin);
        }
        $userData['user_id'] = empty($register)?$has:$register;
        $userData['ctime'] = time();
        $userData['mobile'] = $mobile;

        if($res_login){
            M('user','',C('DB2'))->commit();
            if(!empty($register)){
                $has_marketing =M('marketing','',C('DB2'))->where(['mobile'=>$mobile])->getField('id');
                if($has_marketing){
                    M('marketing','',C('DB2'))->where(['mobile'=>$mobile])->setField('id_delete','2');
                }
            }
            $user = M('user','',C('DB2'))->where(['id'=>$userData['user_id'],'is_delete'=>'1'])->field('id,channel,chat_id')->find();
            if(empty($user['channel'])){
                //$kefu = M('channel','',C('DB2'))->where(['shop_identifier'=>$shop_identifier])->field('shop_identifier,shop_id')->find();
                $gateway = new \Home\Service\Gateway();
                //if(empty($user['channel'])&&$user['chat_id']==1||$user['chat_id']==0) {
                    if(empty($user['channel'])){
                    $shopkeeper_kefu = M('shopkeeper', '', C('DB2'))->where(['shop_idenfier' =>$shop_identifier, 'state' => 1])->order(['ctime desc'])->field('id,account,rid')->select();
                    foreach ($shopkeeper_kefu as $key => $value) {
                        //if ($gateway->isUidOnline($value['account'])==1) {
                            //$kefuid[$value['id']] = $value['id'];///在线客服id
                        //}
                        $domain = strstr($value['rid'], '4');
                        $v2_domain = strstr($value['rid'], '10');
                        if($domain!==false||$v2_domain!==false){
                            $kefuid[$value['id']] = $value['id'];///在线客服id
                        }
                    }
                    $kefuid=array_rand($kefuid,1);
                    if(!empty($kefuid)){
                        M('user','',C('DB2'))->where(['id'=>$userData['user_id'],'is_delete'=>1])->save(['chat_id'=>$kefuid]);
                    }
                }
            }else{
                $kefu = M('channel','',C('DB2'))->where(['chan_id'=>$user['channel']])->field('shop_id')->find();
                //M('user','',C('DB2'))->where(['id'=>$userData['user_id'],'is_delete'=>1])->save(['chat_id'=>$kefu['shop_id']]);
            }

//            $kefudata = M('communication','',C('DB2'))
//                ->where(['shop_id'=>$kefu['shop_id']])
//                ->field('account,nickname')
//                ->find();
//            $add = array(
//                'user_id'=>$kefudata['account'],
//                'user_name'=>$kefudata['nickname'],
//                'receive_id'=>$userData['user_id'],
//                'message'=>'您的专属客服'.$kefudata['nickname'].'已上线，有任何问题可以联系我哦',
//                'send_time'=>time(),
//                'type'=>'1',
//            );
//            M('chat_record_copy','',C('DB2'))->add($add);
            //$this->seed_message($userData['user_id']);
//            $this->get_kefu($userData['user_id'],$shop_identifier);
            $label = M('label','',C('DB2'))->where(['shop_identifier'=>$shop_identifier,'is_dell'=>1,'name'=>'无标签'])->field('id')->find();
            if(empty($user['channel'])){
                M('label_id','',C('DB2'))->add(['user_id'=>$userData['user_id'],'label_id'=>$label['id'],'ctime'=>time()]);
                $gateway = new \Home\Service\Gateway();
                $label = M('user', Null, 'DB2')
                    ->join("u left join label_id l_id on u.id=l_id.user_id")
                    ->join("left join label l on l.id=l_id.label_id")
                    ->join("left join user_identity uid on uid.user_id=u.id")
                    ->where(["u.id" =>$userData['user_id'], 'u.is_delete' => 1])
                    ->order("l.name desc")
                    ->field("l.id,l_id.user_id,l.name,u.username,uid.hold")
                    ->group("u.id")
                    //->fetchSql(true)
                    ->select();
                //$updata_user_list = json_encode($label);
                $data7['type'] = 'update_user_list';
                $data7['data'] = $label;
                $user_chat_id=M('user','','DB2')->where(['id'=>$userData['user_id']])->getField('chat_id');
                $chat_account=M('shopkeeper','','DB2')->where(['id'=>$user_chat_id,'state'=>1])->field('account')->find();
                $gateway->sendToUid($chat_account['account'], json_encode($data7));//像对方发送消息
            }
           if($get['device']=='iOS'){
               $this->seed_message($userData['user_id']);
           }

            $data['ret']='1001';
            $data['code']='注册成功';
            $data['data'] =$userData;
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }else {
            M('user','',C('DB2'))->rollback();
            $data['ret']='1002';
            $data['code']='注册失败';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
    }
    public function msg(){
        $msg = new ChatwithController();
        $res=$msg->message_api('1213','1205','欢迎登陆');
        $res1=$msg->message_api('1214','1205','欢迎登陆');
        var_dump($res);
        var_dump($res1);
    }
    /*
    登录
    */
    public function login(){
        $get = I('data');
        $get = $this->jiemi($get);
        if(!IS_POST){
            $data['ret']='1002';
            $data['code']='NOT POST';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        $shop_identifier=$get['shop_identifier'];
        $mobile 	= $get['mobile'];
        $pwd   		= md5('hxgj'.$get['pwd']);
        $udid = $get['udid'];
        $mobilefirm=$get['mobilefirm'];
        $location  = $get['location'];
        $black_box = $get['black_box'];
        if(empty($location)){
            $data['ret']='1002';
            $data['code']='请打开定位';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            return false;
        }
        if(!preg_match("/1[123456789]{1}\d{9}$/",$mobile)){
            $data['ret']='1002';
            $data['code']='手机号码格式不正确';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            return false;
        }
        $user = M('user','',C('DB2'))->where(array('mobile'=>$mobile,'shop_identifier'=>$shop_identifier,'is_delete'=>'1'))->field('id as user_id,mobile,status,channel,username,chat_id')->find();
        $user_pwd = M('user_login','',C('DB2'))->where(array('user_id'=>$user['user_id'],'shop_identifier'=>$shop_identifier,'status'=>['not in','4']))->field('pwd,status,udid,mobilefirm,lng_lat')->find();
//        var_dump($user_pwd);
//        var_dump($pwd);die;
        if ($user_pwd['status'] == 2) {
            $data['ret']='1002';
            $data['code']='帐户锁定';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            return false;
        }
        if (!$user) {
            $data['ret']='1002';
            $data['code']='账户不存在';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            return false;
        }
        if($user_pwd['pwd'] == $pwd){
            if(empty($user_pwd['udid'])||empty($user_pwd['mobilefirm'])||empty($user_pwd['lng_lat'])){
                $userlogin['udid']=$udid;
                $userlogin['mobilefirm']=$mobilefirm;
                $userlogin['lng_lat']=$location;
                M('user_login','',C('DB2'))->where(array('mobile'=>$mobile,'status'=>['not in','4']))->save($userlogin);
            }
//            $msg = new ChatwithController();
//            $msg->message_api('1213',$user['user_id'],'欢迎登陆');
//            $msg->message_api('1214',$user['user_id'],'欢迎登陆');
            $kefu = M('channel','',C('DB2'))->where(['chan_id'=>$user['channel']])->field('shop_id')->find();
//            $gateway = new \Home\Service\Gateway();
//            if(empty($user['channel'])&&$user['chat_id']==1||$user['chat_id']==0) {
//                $shopkeeper_kefu = M('communication', '', C('DB2'))->where(['shop_identifier' =>$shop_identifier, 'commun_state' => 1])->order(['ctime desc'])->field('shop_id,account')->select();
//                foreach ($shopkeeper_kefu as $key => $value) {
//                    if ($gateway->isUidOnline($value['account'])==1) {
//                        $kefuid[$value['shop_id']] = $value['shop_id'];///在线客服id
//                    }
//                }
//                $kefuid=array_rand($kefuid,1);
//                if(!empty($kefuid)){
//                    M('user','',C('DB2'))->where(['id'=>$user['user_id'],'is_delete'=>1])->save(['chat_id'=>$kefuid]);
//                }
//            }
//            $kefudata = M('communication','',C('DB2'))->where(['shop_id'=>$user['chat_id']])->field('account,nickname')->find();
//            if($kefudata) {
//                $add = array(
//                    'user_id' => $kefudata['account'],
//                    'user_name' => $kefudata['nickname'],
//                    'receive_id' => $user['user_id'],
//                    'receive_name' => empty($user['username'])?" ":$user['username'],
//                    'message' => '您的专属客服' . $kefudata['nickname'] . '已上线，有任何问题可以联系我哦',
//                    'send_time' => time(),
//                    'type' => '1',
//                );
//                M('chat_record_copy', '', C('DB2'))->add($add);
//            }
//            $add_log = array(
//                'user_id'=>$user_pwd['id'],
//                'chat_id'=>$user['chat_id'],
//                'ctime'=>time(),
//            );
//            M('user_chat_now','',C('DB2'))->add($add_log);

            $this->seed_message($user['user_id']);
            if(strpos($location,'lat')!==false){
                $coordinate = explode(',', $location);
                $lat = explode(':', $coordinate[0])[1];
                $lon = explode(':', $coordinate[1])[1];
            }else{
                $lat = explode(',', $location)[0];
                $lon = explode(',', $location)[1];
            }
            if($lat>$lon){
                $res = $this->getAddressComponent($lat,$lon);//经度纬度
            }else{
                $res = $this->getAddressComponent($lon,$lat);//经度纬度
            }
            $login_log =M('user_login_log','',C('DB2'));
            $ip = $this->get_ip2();  // IP 省 市
            $arr = array(
                'login_time'		=>	time(),
                'login_ip'			=>	$ip['ip'],
                'login_position'	=>	$location, //登录坐标，逗号隔开
                'uid'				=> 	$user['user_id'],
                'address'			=>$res['result']['formatted_address'],
                'city'			=>$res['result']['addressComponent']['city'],
                'change_time'       =>time(),
            );
            $has = M('user_login_log','',C('DB2'))->where(array('uid'=>$user['user_id']))->order('change_time desc')->field('address,id')->limit(1)->find();
            if($has['address']==$res['result']['formatted_address']&&$has['ctime']<time()-3600&&!empty($res['result']['formatted_address'])){
                $arr = array(
                    'city'			=>$res['result']['addressComponent']['city'],
                    'change_time'=>time(),
                );
                M('user_login_log','',C('DB2'))->where(array('uid'=>$user['user_id'],'id'=>$has['id']))->save($arr);
            }else{
                if(!empty($res['result']['formatted_address'])&&!empty($location)){
                    $login_log->add($arr);
                }
            }
            $add = array(
                'user_id'=>$user['user_id'],
                'black_box'=>$black_box,
                'ctime'=>time(),
            );
            M('user_black_box','',C('DB2'))->add($add);
            $dec = M('balance_record','',C('DB2'))->where(array('shop_identifier'=>$shop_identifier,'mobile'=>$mobile,'detail'=>'首次登陆分发费用'))->getField('id');
            if(empty($dec)){
                $url = "http://dnqxfv2.hzdouniu.cn/haoxin/deducted";
                $ChargingAdd= array(
                    'shopIdentifier'=>$shop_identifier,
                    'mobile'=>$mobile,
                    'money'=>0.2,
                    'detail'=>'首次登陆分发费用',
                    'type'=>'1',
                    'costType'=>'2',
                );
                $this->curl_post_https($url,$ChargingAdd);
            }
            $data['ret']='1001';
            $data['code']='success';
            $user['username']=empty($user['username'])?'':$user['username'];
            $data['data']=$user;
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }else{
            $data['ret']='1002';
            $data['code']='帐户或密码错误';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
    }
    //自动发送系统消息与还款短信
    static function seed_message($user_id){
        $user_data = M('user','',C('DB2'))->where(['id'=>$user_id,'is_delete'=>1])->field('cert_status,username')->find();
        if($user_data['cert_status']=='1'){
            $content1='尊敬的用户，欢迎您使用本产品，为了您顺利完成借款请先认证个人信息。';
            $content2='近期无待还款';
        }elseif($user_data['cert_status']=='3'){
            $content1='尊敬的'.$user_data['username'].'用户，非常抱歉您的资质审核未通过，感谢您的使用。';
            $content2='近期无待还款';
        }elseif ($user_data['cert_status']=='2'){
            $c_data = M('certificate','',C('DB2'))->where(['borrower_id'=>$user_id])->getField('id');
            if(empty($c_data)){
                $content1='尊敬的'.$user_data['username'].'用户，很高兴的通知您，您的资质已经通过审核，请尽快联系我们的客服人员申请借款吧。';
                $content2='近期无待还款';
            }else{
                $dqr = M('certificate','',C('DB2'))->where(['borrower_id'=>$user_id,'status'=>'1'])->count();
                $dcl =  M('certificate','',C('DB2'))->where(['borrower_id'=>$user_id,'status'=>['in','2,3,4,5,9']])->count();
                $content1='尊敬的'.$user_data['username'].'用户，欢迎登陆，您有'.$dcl.'笔凭证未处理,有'.$dqr.'笔凭证待确认';
                $overdue =  M('certificate','',C('DB2'))->where(['borrower_id'=>$user_id,'status'=>['in','3,5']])->field('id')->select();
                if($overdue){
                    $content2='尊敬的'.$user_data['username'].'用户，您有订单逾期，我们的凭证上传至云合同，会影响您的征信，请及时处理';
                }else{
                    $has =  M('certificate','',C('DB2'))->where(['borrower_id'=>$user_id,'status'=>['in','2,4,9']])->count();
                    if($has>0){
                        $has =  M('certificate','',C('DB2'))->where(['borrower_id'=>$user_id,'status'=>['in','2,4,9']])->field('repayment_time,period_time,status')->select();
                        $time = 0;
                        foreach ($has as $k=>$v){
                            if($v['status']=='2'||$v['status']=='9'){
                                $order_time = $v['repayment_time'];
                            }else{
                                $order_time = $v['period_time'];
                            }
                            $time=$order_time>$time?$order_time:$time;
                        }
                        $content2='尊敬的'.$user_data['username'].'用户，您最近的还款日为'.date('Y-m-d',$time).'。';
                    }else{
                        $content2='近期无待还款';
                    }
                }
            }
        }else{
            $content1='尊敬的'.$user_data['username'].'用户，您的信息正在审核中，请稍等片刻。';
            $content2='近期无待还款';
        }
        $add_msg = array(
            'user_id'=>'5',
            'user_name'=>'系统消息',
            'receive_id'=>$user_id,
            'message'=>$content1,
            'send_time'=>time(),
            'type'=>'1',
        );
        $add_msg1 = array(
            'user_id'=>'6',
            'user_name'=>'还款通知',
            'receive_id'=>$user_id,
            'message'=>$content2,
            'send_time'=>time(),
            'type'=>'1',
        );
        M('chat_record_copy','',C('DB2'))->add($add_msg);
        M('chat_record_copy','',C('DB2'))->add($add_msg1);
    }
    public function login_formsg(){
        $get = I('data');
        $get = $this->jiemi($get);
        if(!IS_POST){
            $data['ret']='1002';
            $data['code']='NOT POST';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        $code=$get['code'];
        $shop_identifier=$get['shop_identifier'];
        $mobile 	= $get['mobile'];
        $pwd   		= md5('hxgj'.$get['pwd']);
        $udid = $get['udid'];
        $mobilefirm=$get['mobilefirm'];
        $location  = $get['location'];
        $black_box = $get['black_box'];
        if(empty($location)){
            $data['ret']='1002';
            $data['code']='请打开定位';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        if(!preg_match("/1[345789]{1}\d{9}$/",$mobile)){
            $data['ret']='1002';
            $data['code']='手机号码格式不正确';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        if(empty($code)){
            $data['ret']='1002';
            $data['code']='验证码不能为空';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        $time = S($mobile.'phone_time');
        $redcode =S($mobile.'phone_verify');
        if($mobile!='15220219931'){
            if(time()-$time>120||$redcode!=$code){
                $data['ret']='1002';
                $data['code']='验证码错误';
                $data = $this->jiami($data);
                $this->return = ['data'=>$data];
                exit;
            }
        }
        $user = M('user','',C('DB2'))->where(array('mobile'=>$mobile,'shop_identifier'=>$shop_identifier,'is_delete'=>1))->field('id as user_id,mobile,status,channel,username,chat_id')->find();
        $user_pwd = M('user_login','',C('DB2'))->where(array('mobile'=>$mobile,'shop_identifier'=>$shop_identifier,'status'=>['not in','4']))->field('pwd,status,udid,mobilefirm,lng_lat')->find();
//        var_dump($user_pwd);
//        var_dump($pwd);die;
        if ($user_pwd['status'] == '2') {
            $data['ret']='1002';
            $data['code']='帐户锁定';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        if (!$user) {
            $data['ret']='1002';
            $data['code']='账户不存在';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        if(empty($user_pwd['udid'])||empty($user_pwd['mobilefirm'])||empty(empty($user_pwd['lng_lat']))){
            $userlogin['udid']=$udid;
            $userlogin['mobilefirm']=$mobilefirm;
            $userlogin['lng_lat']=$location;
            M('user_login','',C('DB2'))->where(array('mobile'=>$mobile,'status'=>['not in','4']))->save($userlogin);
        }
        $kefu = M('channel','',C('DB2'))->where(['chan_id'=>$user['channel']])->field('shop_id')->find();
        $gateway = new \Home\Service\Gateway();
        if(empty($user['channel'])&&$user['chat_id']==1) {
            $shopkeeper_kefu = M('communication', '', C('DB2'))->where(['shop_identifier' => $kefu['shop_identifier'], 'commun_state' => 1])->order(['ctime desc'])->field('shop_id,account')->select();
            foreach ($shopkeeper_kefu as $key => $value) {
                switch ($gateway->isUidOnline($value['account'])) {
                    case 1:
                        $kefuid[] = $value['shop_id'];///在线客服id
                        break;
                }
            }
            $kefuid=array_rand($kefuid,1);
            if(!empty($kefuid)){
                M('user','',C('DB2'))->where(['id'=>$user['user_id'],'is_delete'=>1])->save(['chat_id'=>$kefuid]);
            }
        }

        $kefudata = M('communication','',C('DB2'))->where(['shop_id'=>$user['chat_id']])->field('account,nickname')->find();
        if($kefudata) {
            $add = array(
                'user_id' => $kefudata['account'],
                'user_name' => $kefudata['nickname'],
                'receive_id' => $user['user_id'],
                'receive_name' => empty($user['username'])?" ":$user['username'],
                'message' => '您的专属客服' . $kefudata['nickname'] . '已上线，有任何问题可以联系我哦',
                'send_time' => time(),
                'type' => '1',
            );
            M('chat_record_copy', '', C('DB2'))->add($add);
        }
        $add_log = array(
            'user_id'=>$user_pwd['id'],
            'chat_id'=>$kefu['shop_id'],
            'ctime'=>time(),
        );
        M('user_chat_now','',C('DB2'))->add($add_log);
        $this->seed_message($user['user_id']);
        $add = array(
            'user_id'=>$user['user_id'],
            'black_box'=>$black_box,
            'ctime'=>time(),
        );
        M('user_black_box','',C('DB2'))->add($add);
//        $this->get_kefu($user['user_id'],$shop_identifier);
        $dec = M('balance_record','',C('DB2'))->where(array('shop_identifier'=>$shop_identifier,'mobile'=>$mobile,'detail'=>'首次登陆分发费用'))->getField('id');
        if(empty($dec)){
            $url = "http://dnqxfv2.hzdouniu.cn/haoxin/deducted";
            $ChargingAdd= array(
                'shopIdentifier'=>$shop_identifier,
                'mobile'=>$mobile,
                'money'=>0.2,
                'detail'=>'首次登陆分发费用',
                'type'=>'1',
                'costType'=>'2',
            );
            $this->curl_post_https($url,$ChargingAdd);
        }
        $data['ret']='1001';
        $data['code']='success';
        $data['data']=$user;
        $data = $this->jiami($data);
        $this->return = ['data'=>$data];
        exit();
    }
    public function login_log(){
        $get = I('data');
        $get = $this->jiemi($get);
        if(!IS_POST){
            $data['ret']='1002';
            $data['code']='NOT POST';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        $user_id = $get['user_id'];
        $location  = $get['location'];
        $user = M('user','',C('DB2'))->where(['id'=>$user_id,'is_delete'=>'1'])->field('id as user_id')->find();
        if(strpos($location,'lat')!==false){
            $coordinate = explode(',', $location);
            $lat = explode(':', $coordinate[0])[1];
            $lon = explode(':', $coordinate[1])[1];
        }else{
            $lat = explode(',', $location)[0];
            $lon = explode(',', $location)[1];
        }
        if($lat>$lon){
            $res = $this->getAddressComponent($lat,$lon);//经度纬度
        }else{
            $res = $this->getAddressComponent($lon,$lat);//经度纬度
        }
        $login_log =M('user_login_log','',C('DB2'));
        $ip = $this->get_ip2();  // IP 省 市
        $arr = array(
            'login_time'		=>	time(),
            'login_ip'			=>	$ip['ip'],
            'login_position'	=>	$location, //登录坐标，逗号隔开
            'uid'				=> 	$user['user_id'],
            'address'			=>$res['result']['formatted_address'],
            'city'			=>$res['result']['addressComponent']['city'],
            'change_time'       =>time(),
        );
        $has = M('user_login_log','',C('DB2'))->where(array('uid'=>$user['user_id']))->order('change_time desc')->field('address,id')->limit(1)->find();
        if($has['address']==$res['result']['formatted_address']&&$has['ctime']<time()-3600&&!empty($res['result']['formatted_address'])){
            $arr = array(
                'change_time'=>time(),
            );
            M('user_login_log','',C('DB2'))->where(array('uid'=>$user['user_id'],'id'=>$has['id']))->save($arr);
        }else{
            if(!empty($res['result']['formatted_address'])&&!empty($location)){
                $login_log->add($arr);
            }
        }
        $data['ret']='1001';
        $data['code']='success';
        $data = $this->jiami($data);
        $this->return = ['data'=>$data];
        exit();
    }
    /*
    找回密码
    * 逻辑过程 : 填写手机号码->获取验证码->跳转密码页->输入两次密码->比对密码一致，请求修改密码接口
     */
    public function retpwd(){
        $get = I('data');
        $get = $this->jiemi($get);
        if(!IS_POST){
            $data['ret']='1002';
            $data['code']='NOT POST';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        $mobile 	= $get['mobile'];
        $pwd   		= md5('hxgj'.$get['pwd']);
        $code = $get['code'];
        $time = S($mobile.'backpwd_time');
        $redcode = S($mobile.'backpwd_verify');
        if(!preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/",$get['pwd'])){
            $data['ret']='1002';
            $data['code']='密码必须由字母和数字组成(6-16位)';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        if(time()-$time>120||$redcode!=$code){
            $data['ret']='1002';
            $data['code']='验证码错误';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit;
        }
        S($mobile.'backpwd_time',null);
        S($mobile.'backpwd_verify',null);
        $save['pwd'] = $pwd;
        $user = M('user_login','',C('DB2'))->where(array('mobile'=>$mobile,'status'=>['not in','4']))->save(array('pwd'=>$pwd));
        if ($user==false||$user) {
            $data['ret']='1001';
            $data['code']='找回密码成功';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        } else {
            $data['ret']='1002';
            $data['code']='找回密码失败';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
    }
//修改登陆密码
    Public function editpwd(){
        $get = I('data');
        $get = $this->jiemi($get);
        if(!IS_POST){
            $data['ret']='1002';
            $data['code']='NOT POST';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
        $shop_identifier = $get['shop_identifier'];
        $newpwd = md5('hxgj'.$get['newpwd']);
        $user_id = $get['user_id'];
        $code = $get['code'];
        $mobile = M('user','',C('DB2'))->where(array('id'=>$user_id,'shop_identifier'=>$shop_identifier,'is_delete'=>'1'))->getField('mobile');

        $time = S($mobile.'editpwd_time');
        $redcode = S($mobile.'editpwd_verify');
//        if(!preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/",$get['newpwd'])){
//            $data['ret']='1002';
//            $data['code']='密码必须由字母和数字组成(6-16位)';
//            $data = $this->jiami($data);
//            $this->return = ['data'=>$data];
//            exit();
//        }
        if(time()-$time>120||$redcode!=$code){
            $data['ret']='1002';
            $data['code']='验证码错误';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit;
        }
        S($mobile.'editpwd_time',null);
        S($mobile.'editpwd_verify',null);
        $model = M('user','',C('DB2'));
        $res = $model->where(array('id'=>$user_id))->save(array('pwd'=>$newpwd));
        if($res){
            $mobile = M('user','',C('DB2'))->where(array('id'=>$user_id,'shop_identifier'=>$shop_identifier,'is_delete'=>'1'))->getField('mobile');
            $content = '您已经通过手机号验证进行帐号密码找回，原密码将不能使用。如有疑问请致电客服。';
            $this->cl_sms($mobile,$content,$shop_identifier);
            $data['ret']='1001';
            $data['code']='修改成功';
            $data = $this->jiami($data);
            $this->return = ['data'=>$data];
            exit();
        }
    }
    public function first_index(){
        $this->display();
    }
    public function acc_examine(){
        $mobile = I('mobile');
        $name = I('name');
        $id_card = I('id_card');
        $channel =I('channel');
        if(empty($channel)){
            $data['ret']='1002';
            $data['code']='缺少渠道标识';
            echo json_encode($data);
            exit();
        }
        if(empty($mobile)||empty($name)||empty($id_card)){
            $data['ret']='1002';
            $data['code']='缺少用户信息';
            echo json_encode($data);
            exit();
        }
        $shop_identifier = M('channel','',C('DB2'))->where(array('chan_id'=>$channel))->getField('shop_identifier');
        $user_data = M('user','',C('DB2'))->where(['mobile'=>$mobile,'shop_identifier'=>$shop_identifier,'is_delete'=>'1'])->find();
        if(empty($user_data)){
            $data['ret']='1002';
            $data['code']='请先注册';
            echo json_encode($data);
            exit();
        }
        if($user_data['cert_status']=='3'||$user_data['cert_status']=='2'||$user_data['cert_status']=='4'){
            $data['ret']='1002';
            $data['code']='请勿重复认证';
            echo json_encode($data);
            exit();
        }
            $sp = M('user_risk_rule','',C('DB2'))->where(['shop_identifier'=>$user_data['shop_identifier'],'rule_name'=>'芝麻认证是否开启'])->getField('rule_detail');
            if($sp=='开启'){
                $zm = new XycruleController();
                $res_zm = $zm->k0042($name, $id_card);
                $res_zm = json_decode($res_zm, true);
                if ($res_zm['status'] == '1003' || $res_zm['status'] == '1002') {
                    $data['ret'] = '1002';
                    $data['code'] = $res_zm['result'];
                    echo json_encode($data);
                    exit();
                }
                if ($res_zm['result'] == 'nopass') {
                    M('user', '', C('DB2'))->where(array('mobile' => $mobile, 'shop_identifier' => $shop_identifier,'is_delete'=>'1'))->save(['cert_status' => '3', 'username' => $name, 'identity_num' => $id_card]);
                    M('apply_order', '', C('DB2'))->where(array('user_mobile' => $mobile))->save(array('apply_user' => $name));
                }
            }

            $date = strtotime(substr($id_card, 6, 8));
            //获得出生年月日的时间戳
            $today = strtotime('today');
            //获得今日的时间戳
            $diff = floor(($today - $date) / 86400 / 365);
            //得到两个日期相差的大体年数
            //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
            $age = strtotime(substr($id_card, 6, 8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff;
            $url_age = 'https://jallzf.miaodaoxj.com:444/jyyjr/checkX0001?age=' . $age.'&shopIdentifier='.$shop_identifier;
            $res = $this->get_curl($url_age);
            $res = json_decode($res, true);
            if ($res['message'] == '命中') {
                M('apply_order', '', C('DB2'))->where(array('user_mobile' => $mobile))->save(array('apply_user' => $name));
            }
            $address = $this->getidecardaddress($id_card);
            $url_address = 'https://jallzf.miaodaoxj.com:444/jyyjr/checkK0031?address=' . urlencode($address['city']).'&shopIdentifier='.$shop_identifier;
            $res = $this->get_curl($url_address);
            $res = json_decode($res, true);
            if ($res['message'] == '命中') {
                M('apply_order', '', C('DB2'))->where(array('user_mobile' => $mobile))->save(array('apply_user' => $name));
            }
            $url_mobile = 'https://jallzf.miaodaoxj.com:444/jyyjr/checkK0039?mobile=' . $mobile;
            $res = $this->get_curl($url_mobile);
            $res = json_decode($res, true);
            if ($res['data']['isOverdue'] === true) {
                M('apply_order', '', C('DB2'))->where(array('user_mobile' => $mobile))->save(array('apply_user' => $name));
            }
            M('user', '', C('DB2'))->where(array('mobile' => $mobile, 'shop_identifier' => $shop_identifier,'is_delete'=>'1'))->save(['cert_status' => '1', 'username' => $name, 'identity_num' => $id_card]);
            M('apply_order', '', C('DB2'))->where(array('user_mobile' => $mobile))->save(array('apply_user' => $name));
            $data['ret'] = '1001';
            $data['code'] = '恭喜，您已经通过审核';
            echo json_encode($data);
            exit();
    }


    function getidecardaddress($idcard){
        $data = idcardaddress($idcard);
//        var_dump($data);die;
//        if(mb_strpos($data['city'],'内蒙古自治区')!==false){
//            $position='内蒙古自治区';
//        }elseif(mb_strpos($data['city'],'新疆维吾尔自治区')!==false){
//            $position='新疆维吾尔自治区';
//        }elseif(mb_strpos($data['city'],'广西壮族自治区')!==false){
//            $position='广西壮族自治区';
//        }elseif(mb_strpos($data['city'],'宁夏回族自治区')!==false){
//            $position='宁夏回族自治区';
//        }elseif(mb_strpos($data['city'],'西藏自治区')!==false){
//            $position='西藏自治区';
//        }else{
//            $city = mb_strpos($data['city'],'省');
//            $data['city'] = substr($data['city'],$city+7);
//            $city    =mb_strpos($data['city'],'市');
//            if($city===false){
//                $xian=mb_strpos($data['city'],'县');
//                if($xian===false){
//                    $qu=mb_strpos($data['city'],'区');
//                    if($qu===false){
//                        $cun=mb_strpos($data['city'],'村');
//                        if($cun===false){
//                            $province=mb_strpos($data['city'],'省');
//                            $data['city']=mb_substr($data['city'],0,($province+1),'utf-8');
//                        }else{
//                            $data['city']=mb_substr($data['city'],0,($cun+1),'utf-8');
//                        }
//                    }else{
//                        $data['city']=mb_substr($data['city'],0,($qu+1),'utf-8');
//                    }
//                }else{
//                    $data['city']=mb_substr($data['city'],0,($xian+1),'utf-8');
//                }
//            }else{
//                $data['city']=mb_substr($data['city'],0,($city+1),'utf-8');
//            }
//        }
//        echo $data;
        return $data;
    }
    function curl_post($url,$data,$header,$post=1)
    {
        //初始化curl
        $ch = curl_init();
        //参数设置
        $res = curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, $post);
        if ($post)
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $result = curl_exec($ch);
        //连接失败
        return $result;
    }
    static function cl_sms($mobile, $content,$shop_identifier)
    {
        date_default_timezone_set('PRC');//设置时区
        $url = 'https://smssh1.253.com/msg/send/json';
        $data['account'] = 'N3075640';
        $data['password'] = 'C8gWliKHwneaf5';
        $app_name = M('merchant','',C('DB2'))->where(['shop_identifier'=>$shop_identifier])->getField('merchant_name');
        $data['msg'] = '【'.$app_name.'】' . $content;
//        $data['msg'] = '【信用查】' . $content;
        $data['phone'] = $mobile;
        $data['sendtime'] = date('YmdHi');
        $data['report'] = 'true';
        $header = array('Content-Type:application/json;charset=utf-8');
        $result = self::set_curl($url, json_encode($data), $header);
        $res = json_decode($result, true);
        if ($res['code'] == '0') {
            $add_news = array(
                'shop_identifier'=>$shop_identifier,
                'mobile'=>$mobile,
                'result'=>'1001',
                'ctime'=>time(),
                'content'=>$content,
            );
            M('user_sms_record','',C('DB2'))->add($add_news);
            return true;
        } else {
            $add_news = array(
                'shop_identifier'=>$shop_identifier,
                'mobile'=>$mobile,
                'result'=>$res['errorMsg'],
                'ctime'=>time(),
                'content'=>$content,
            );
            M('user_sms_record','',C('DB2'))->add($add_news);
            return $res['errorMsg'];
        }
    }
    public function get_curl($url = '',$data='',$header='')
    {

        $ch = curl_init();
        if (!empty($header)) {
//            $header=array('Content-type: application/json','charset:utf-8'); 示例
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, '1');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        //禁用后cURL将终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        if (curl_error($ch)) {
            return '错误信息:' . curl_error($ch);
        }
        curl_close($ch);
        return $res;
    }
    private function get_ip2(){
        $ip = '';
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($ip = $_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } elseif (!empty(getenv('HTTP_X_FORWARDER_FOR'))) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (!empty(getenv('HTTP_CLIENT_IP'))) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty(getenv('REMOTE_ADDR'))) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = 'unknow_id';
        }
        $url = 'http://apis.juhe.cn/ip/ip2addr?ip='.$ip.'&key=e9c27d80d4eeeba052307682ef10c60b';
        $res = $this->get_curl($url);
        $res = json_decode($res,true);
        $data =  $this->ipaddress($res['result']['area']);
        $data['ip'] =$ip;
        return $data;
    }
    function ipaddress($area){
        $city = mb_strpos($area,'省');
        $city = substr($area,$city+7);
        $shenfen    =str_replace($city,'',$area);
        $data['city']=$city;
        $data['shenfen']=$shenfen;
        return $data;
    }
    /**
     * @param string $url 上传地址
     * @param array $data 上传数组
     * @param string $header 头文件设置
     */
    public function set_curl($url, $data = array(), $header = '')
    {
        $ch = curl_init();
        if (!empty($header)) {
//            $header=array('Content-type: application/json','charset:utf-8'); 示例
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, '1');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        //禁用后cURL将终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        if (curl_error($ch)) {
            return '错误信息:' . curl_error($ch);
        }
        curl_close($ch);
        return $res;
    }
    /*
     * 信用卡需要的个人信息接口
     */
    public function credit_card_userInfo(){
        $get = I('data');
        $get = $this->jiemi($get);
        $user_id=$get['user_id'];
        $shop_identifier=$get['shop_identifier'];
        if(empty($user_id)){
            $data['ret'] = '1002';
            $data['code'] = '请先登录，';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        if(empty($shop_identifier)){
            $data['ret'] = '1002';
            $data['code'] = '商户号异常，';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
        $user = M('user', Null, 'DB2')->where(['id'=>$user_id,'shop_identifier'=>$shop_identifier])->field('username,mobile,identity_num')->find();//是否属于自己的用户
        if($user){
            $data['ret'] = '1001';
            $data['code'] = 'success，';
            $data['data'] =$user;
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }else{
            $data['ret'] = '1002';
            $data['code'] = '数据异常，';
            $data1 = $this->jiami($data);
            $this->return = ['data' => $data1];
            return false;
        }
    }
    /*
     * 语音验证码
     * $mobile 手机号
     */
    public function voice_code($mobile,$code){
//        $code=(string)rand(1000,9999);
//        $mobilecode="$code[0] $code[1] $code[2] $code[3]";
//        S($mobile.'phonechang_verify',$code);
//        S($mobile.'phonechang_time',time());
        $url="http://xycshop.dstlkj.com/ChatApi/voice_code?phone=$mobile&code=".$code;
        $header = array('Content-Type:application/json;charset=utf-8');
        $result = self::get_curl($url,'',$header);
        return json_decode($result,true);
//        if($result['code']=='1001'){
//            $data['ret']='1001';
//            $data['code']='语音验证码已成功发送,请注意接听';
//            echo json_encode($data);
//            exit;
//        }else{
//            $data['ret']='1002';
//            $data['code']='发送失败,请联系管理员';
//            echo json_encode($data);
//            exit;
//        }
    }
    public function verify1($validate, $user) {
        $params = array();
        $params["captchaId"] = 'b25384ea5b4c4d10ac879889a7dde99c';
        $params["validate"] = $validate;
        $params["user"] = $user;
        // 公共参数
        $params["secretId"] = '64e7487ba293a4c5013e8e32d284fc64';
        $params["version"] = 'v2';
        $params["timestamp"] = sprintf("%d", round(microtime(true)*1000));// time in milliseconds
        $params["nonce"] = sprintf("%d", rand()); // random int
        $params["signature"] = $this->sign('11d506f8f7d3c60d42437f24d1641f0c', $params);

//        var_dump($params);
        $result = $this->send_http_request($params);
        return array_key_exists('result', $result) ? $result['result'] : false;
    }

    /**
     * 计算参数签名
     * @param $secret_key 密钥对key
     * @param $params 请求参数
     */
    private function sign($secret_key, $params){
        ksort($params); // 参数排序
        $buff="";
        foreach($params as $key=>$value){
            $buff .=$key;
            $buff .=$value;
        }
        $buff .= $secret_key;
        return md5($buff);
    }

    /**
     * 发送http请求
     * @param $params 请求参数
     */
    private function send_http_request($params){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://c.dun.163yun.com/api/v2/verify');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, YIDUN_CAPTCHA_API_TIMEOUT);
        curl_setopt($ch, CURLOPT_TIMEOUT, YIDUN_CAPTCHA_API_TIMEOUT);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));

        /*
         * Returns TRUE on success or FALSE on failure.
         * However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
         */
        $result = curl_exec($ch);
        // var_dump($result);

        if(curl_errno($ch)){
            $msg = curl_error($ch);
            curl_close($ch);
            return array("error"=>500, "msg"=>$msg, "result"=>false);
        }else{
            curl_close($ch);
            return json_decode($result, true);
        }
    }
    public function mobile_verfiy(){
  //      $data = M('user','',C('DB2'))->where(array('mobile_verify'=>'2'))->field('vid,mobile')->limit(6)->order('rand()')->select();
        $user_id=I('user_id');
        $data = array(
            0=>array('user_id'=>$user_id),
        );
        if(empty($data)){
            exit();
        }
        foreach ($data as $k=>$v) {
            //var_dump($v['user_id']);
            $task_id = M('tdyyshd_report', '', C('DB2_ZX'))->where(array('user_id' => $v['user_id'],'code'=>'0'))->field('task_id,ctime')->find();
            if ($task_id['ctime'] > time() - 5 * 60) {
                continue;
            }
            if (empty($task_id['task_id'])) {
                M('user', '', C('DB2'))->where(array('user_id' => $v['user_id']))->save(array('mobile_verify' => '4'));
                continue;
            }
            $post_data['task_id'] = $task_id['task_id'];
            $url = 'https://api.shujumohe.com/octopus/task.unify.query/v3?partner_code=sharedcash&partner_key=dfc99c9bad014db59fc7ed6d4187ae49';
            $result = $this->post2($url, $post_data);
            $result = json_decode($result, true);
//            var_dump($result);die;
            if ($result['code'] != '0') {
                M('user', '', C('DB2'))->where(array('user_id' => $v['user_id']))->save(array('mobile_verify' => '4'));
                $this->return = ['code' => '0', 'message' => 'success'];
                exit;
            }
            $has_data3 = M('mobile_callrecord', '', C('NTH'))->where(array('mymobile' => $v['mobile']))->getField('id');
            if (!$has_data3) {
                $data = array(
                    'user_id' => $v['user_id'],
                    'mobile' => $result['data']['task_data']['base_info']['user_number'],
                    'register_time' => strtotime($result['data']['task_data']['account_info']['net_time']),
                    'net_age' => $result['data']['task_data']['account_info']['net_age'],
                    'vip_level' => $result['data']['task_data']['account_info']['crevel'],
                    'idcard' => $result['data']['task_data']['base_info']['cert_num'],
                    'score' => $result['data']['task_data']['account_info']['credit_point'],
                    'amount' => $result['data']['task_data']['account_info']['account_balance'],
                    'cert_addr' => $result['data']['task_data']['base_info']['cert_addr'],
                    'user_name' => $result['data']['task_data']['base_info']['user_name'],
                    'ctime' => time(),
                );
                $reportdataid = M('mobile_basicinfo', '', C('DB2_ZX'))->add($data);

                // print_r($reportdataid);die;
                foreach ($result['data']['task_data']['bill_info'] as $key => $value) {
                    $billinfodata = array(
                        'user_id' => $v['user_id'],
                        'mobile' => $result['data']['task_data']['base_info']['user_number'],
                        'bill_discount' => $result['data']['task_data']['bill_info'][$key]['bill_discount'],
                        'bill_fee' => $result['data']['task_data']['bill_info'][$key]['bill_fee'],
                        'bill_cycle' => $result['data']['task_data']['bill_info'][$key]['bill_cycle'],
                        'paid_amount' => $result['data']['task_data']['bill_info'][$key]['paid_amount'],
                        'unpaid_amount' => $result['data']['task_data']['bill_info'][$key]['unpaid_amount'],
                        'breach_amount' => $result['data']['task_data']['bill_info'][$key]['breach_amount'],
                        'bill_total' => $result['data']['task_data']['bill_info'][$key]['bill_total'],
                    );
                    $billinfoid = M('mobile_bill', '', C('DB2_ZX'))->add($billinfodata);
                    foreach ($result['data']['task_data']['bill_info'][$key]['bill_record'] as $a => $b) {
                        $billrecorddata = array(
                            'billinfoid' => $billinfoid,
                            'fee_name' => $result['data']['task_data']['bill_info'][$key]['bill_record'][$a]['fee_name'],
                            'fee_amount' => $result['data']['task_data']['bill_info'][$key]['bill_record'][$a]['fee_amount'],
                            'fee_category' => $result['data']['task_data']['bill_info'][$key]['bill_record'][$a]['fee_category'],
                            'user_number' => $result['data']['task_data']['bill_info'][$key]['bill_record'][$a]['user_number'],
                        );
                        $billrecorddatanum[$a] = $billrecorddata;
                    }
                    M('billinfo_record', '', C('DB2_ZX'))->addALL($billrecorddatanum);
                    $billrecorddatanum = array();
                }
                unset($billrecorddatanum);
                foreach ($result['data']['task_data']['payment_info'] as $g => $h) {
                    $rechargedata = array(
                        'mobile' => $result['data']['task_data']['base_info']['user_number'],
                        'pay_date' => strtotime($result['data']['task_data']['payment_info'][$g]['pay_date']),
                        'pay_channel' => $result['data']['task_data']['payment_info'][$g]['pay_channel'],
                        'pay_fee' => $result['data']['task_data']['payment_info'][$g]['pay_fee'],
                        'pay_type' => $result['data']['task_data']['payment_info'][$g]['pay_type'],
                    );
                    $rechargedatanum[$g] = $rechargedata;
                }
                M('mobilepayment_info', '', C('DB2_ZX'))->addAll($rechargedatanum);
                unset($rechargedatanum);

                foreach ($result['data']['task_data']['package_info']['package_detail'] as $i => $j) {

                    $package_infodata = array(
                        'mobile' => $result['data']['task_data']['base_info']['user_number'],
                        'brand_name' => $result['data']['task_data']['package_info']['brand_name'],
                        'pay_type' => $result['data']['task_data']['package_info']['pay_type'],
                        'fee_cycle' => strtotime($result['data']['task_data']['package_info']['package_detail'][$i]['fee_cycle']),
                        'package_name' => $result['data']['task_data']['package_info']['package_detail'][$i]['package_name'],
                        'invalid_time' => strtotime($result['data']['task_data']['package_info']['package_detail'][$i]['invalid_time']),
                        'category' => $result['data']['task_data']['package_info']['package_detail'][$i]['category'],
                        'package_fee' => $result['data']['task_data']['package_info']['package_detail'][$i]['package_fee'],
                        'effect_time' => strtotime($result['data']['task_data']['package_info']['package_detail'][$i]['effect_time']),
                    );
                    $package_detaildatanum[$i] = $package_infodata;
                }
                M('mobile_businessinfo', '', C('DB2_ZX'))->addALL($package_detaildatanum);
                unset($package_detaildatanum);

                foreach ($result['data']['task_data']['call_info'] as $k => $l) {
                    $callinfo = array(
                        'user_id' => $v['user_id'],
                        'mobile' => $result['data']['task_data']['base_info']['user_number'],
                        'total_call_count' => $result['data']['task_data']['call_info'][$k]['total_call_count'],
                        'total_call_time' => $result['data']['task_data']['call_info'][$k]['total_call_time'],
                        'total_fee' => $result['data']['task_data']['call_info'][$k]['total_fee'],
                        'call_cycle' => strtotime($result['data']['task_data']['call_info'][$k]['call_cycle']),
                        'ctime' => time(),
                    );
                    $callinfoid = M('call_info', '', C('DB2_ZX'))->add($callinfo);
                    foreach ($result['data']['task_data']['call_info'][$k]['call_record'] as $n => $m) {
                        $callinforecoded = array(
                            'callinfoid' => empty($callinfoid) ? '' : $callinfoid,
                            'mymobile' => $result['data']['task_data']['base_info']['user_number'],
                            'call_cost' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_cost']) ? '' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_cost'],
                            'call_land_type' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_land_type']) ? '' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_land_type'],
                            'call_long_distance' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_long_distance']) ? '0' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_long_distance'],
                            'call_type_name' => $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_type_name'],
                            'call_roam_cost' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_roam_cost']) ? '0' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_roam_cost'],
                            'call_other_number' => $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_other_number'],
                            'call_start_time' => empty(strtotime($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_start_time'])) ? '' : strtotime($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_start_time']),
                            'call_discount' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_discount']) ? '0' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_discount'],
                            'call_address' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_address']) ? '' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_address'],
                            'call_time' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_time']) ? '' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_time'],
                        );
                        $callinforecodednum[$n] = $callinforecoded;
//                        var_dump($callinforecoded);
                        $callinforecoded = array();
                    }
                    var_dump($callinforecodednum);
                    $res=M('mobile_callrecord', '', C('NTH'))->addALL($callinforecodednum);
//                    var_dump($res);
                    $callinforecodednum = array();
                }
            }

        }
    }
    public function mobile_verfiy1(){
  //      $data = M('user','',C('DB2'))->where(array('mobile_verify'=>'2'))->field('vid,mobile')->limit(6)->order('rand()')->select();
        $user_id=I('user_id');
        $data = array(
            0=>array('user_id'=>$user_id),
        );
        if(empty($data)){
            exit();
        }
        foreach ($data as $k=>$v) {
            //var_dump($v['user_id']);
            $task_id = M('tdyyshd_report', '', C('DB2_ZX'))->where(array('user_id' => $v['user_id'],'code'=>'0'))->field('task_id,ctime')->find();
            if ($task_id['ctime'] > time() - 5 * 60) {
                continue;
            }
            if (empty($task_id['task_id'])) {
                M('user', '', C('DB2'))->where(array('user_id' => $v['user_id']))->save(array('mobile_verify' => '4'));
                continue;
            }
            $post_data['task_id'] = $task_id['task_id'];
            $url = 'https://api.shujumohe.com/octopus/task.unify.query/v3?partner_code=sharedcash&partner_key=dfc99c9bad014db59fc7ed6d4187ae49';
            $result = $this->post2($url, $post_data);
            $result = json_decode($result, true);
//            var_dump($result);die;
            if ($result['code'] != '0') {
                M('user', '', C('DB2'))->where(array('user_id' => $v['user_id']))->save(array('mobile_verify' => '4'));
                $this->return = ['code' => '0', 'message' => 'success'];
                exit;
            }
            $has_data3 = M('mobile_callrecord', '', C('NTH'))->where(array('mymobile' => $v['mobile']))->getField('id');
            if (!$has_data3) {

                foreach ($result['data']['task_data']['call_info'] as $k => $l) {
                    $callinfo = array(
                        'user_id' => $v['user_id'],
                        'mobile' => $result['data']['task_data']['base_info']['user_number'],
                        'total_call_count' => $result['data']['task_data']['call_info'][$k]['total_call_count'],
                        'total_call_time' => $result['data']['task_data']['call_info'][$k]['total_call_time'],
                        'total_fee' => $result['data']['task_data']['call_info'][$k]['total_fee'],
                        'call_cycle' => strtotime($result['data']['task_data']['call_info'][$k]['call_cycle']),
                        'ctime' => time(),
                    );
                    $callinfoid = M('call_info', '', C('DB2_ZX'))->add($callinfo);
                    foreach ($result['data']['task_data']['call_info'][$k]['call_record'] as $n => $m) {
                        $callinforecoded = array(
                            'callinfoid' => empty($callinfoid) ? '' : $callinfoid,
                            'mymobile' => $result['data']['task_data']['base_info']['user_number'],
                            'call_cost' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_cost']) ? '' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_cost'],
                            'call_land_type' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_land_type']) ? '' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_land_type'],
                            'call_long_distance' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_long_distance']) ? '0' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_long_distance'],
                            'call_type_name' => $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_type_name'],
                            'call_roam_cost' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_roam_cost']) ? '0' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_roam_cost'],
                            'call_other_number' => $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_other_number'],
                            'call_start_time' => empty(strtotime($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_start_time'])) ? '' : strtotime($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_start_time']),
                            'call_discount' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_discount']) ? '0' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_discount'],
                            'call_address' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_address']) ? '' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_address'],
                            'call_time' => empty($result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_time']) ? '' : $result['data']['task_data']['call_info'][$k]['call_record'][$n]['call_time'],
                        );
                        $callinforecodednum[$n] = $callinforecoded;
//                        var_dump($callinforecoded);
                        $callinforecoded = array();
                    }
                    var_dump($callinforecodednum);
                    $res=M('mobile_callrecord', '', C('NTH'))->addALL($callinforecodednum);
//                    var_dump($res);
                    $callinforecodednum = array();
                }
            }

        }
    }
    function post2($url, $data)
    {//file_get_content

        $postdata = http_build_query(
            $data
        );
        $opts = array('http' =>
            array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );
        $context = stream_context_create($opts);
        $result = file_get_contents($url, false, $context);
        return $result;
    }
    /**
     * 发起二次校b25384ea5b4c4d10ac879889a7dde99c 验请求
     * @param $validate 二次校验数据
     * @param $user 用户信息
     */

    public function verifyy($validate, $user) {
        $params = array();
        $params["captchaId"] = 'b25384ea5b4c4d10ac879889a7dde99c';
        $params["validate"] = $validate;
        $params["user"] = $user;
        // 公共参数
        $params["secretId"] = '64e7487ba293a4c5013e8e32d284fc64';
        $params["version"] = 'v2';
        $params["timestamp"] = sprintf("%d", round(microtime(true)*1000));// time in milliseconds
        $params["nonce"] = sprintf("%d", rand()); // random int
        $params["signature"] = $this->signn('11d506f8f7d3c60d42437f24d1641f0c', $params);

        //var_dump($params);
        $result = $this->send_http_requestt($params);
        return array_key_exists('result', $result) ? $result['result'] : false;
    }

    /**
     * 计算参数签名
     * @param $secret_key 密钥对key
     * @param $params 请求参数
     */
    public function signn($secret_key, $params){
        ksort($params); // 参数排序
        $buff="";
        foreach($params as $key=>$value){
            $buff .=$key;
            $buff .=$value;
        }
        $buff .= $secret_key;
        return md5($buff);
    }

    /**
     * 发送http请求
     * @param $params 请求参数
     */
    public function send_http_requestt($params){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://c.dun.163yun.com/api/v2/verify');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, YIDUN_CAPTCHA_API_TIMEOUT);
        curl_setopt($ch, CURLOPT_TIMEOUT, YIDUN_CAPTCHA_API_TIMEOUT);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));

        /*
         * Returns TRUE on success or FALSE on failure.
         * However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
         */
        $result = curl_exec($ch);
        // var_dump($result);

        if(curl_errno($ch)){
            $msg = curl_error($ch);
            curl_close($ch);
            return array("error"=>500, "msg"=>$msg, "result"=>false);
        }else{
            curl_close($ch);
            return json_decode($result, true);
        }
    }
}